<template>
  <div>
    <!-- 添加按钮 -->
    <el-button type="primary" size="default" icon="el-icon-plus" style="margin-bottom: 10px;"
      @click="showDialog">添加</el-button>

    <!-- 表格 -->
    <el-table :data="tableData" border v-loading="loading" style="width: 100%;">
      <!-- 序号 -->
      <el-table-column type="index" width="50" label="序号" align="center">
      </el-table-column>
      <!-- 名称 -->
      <el-table-column prop="tmName" label="品牌名称" width="180" align="center">
      </el-table-column>
      <!-- LOGO -->
      <el-table-column prop="logoUrl" label="品牌LOGO" width="" align="center">
        <template slot-scope="{row}">
          <img :src="row.logoUrl" alt="" style="width: 100px;height: 60px;">
        </template>
      </el-table-column>
      <!-- 操作 -->
      <el-table-column label="操作" width="180">
        <template slot-scope="{row}">
          <el-button size="mini" type="warning" icon="el-icon-edit" @click="handleEdit(row)">编辑</el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <!-- 如果写了.sync 会自动更新pageInfo.page中的值，因此不需要手动更新 -->
    <!-- 因此绑定事件的时候只需要取管发请求，不用去管更新页码 -->
    <el-pagination @current-change="getPageList" @size-change="getPageList" style="margin-top: 20px;text-align: center;"
      :current-page.sync="pageInfo.page" :page-sizes="[3, 5, 10]" :page-size.sync="pageInfo.limit"
      layout="prev, pager, next, jumper ,->,sizes,total" :total="pageInfo.total" :pager-count="7">
    </el-pagination>


    <!-- 弹出层 -->
    <el-dialog :title="editType" :visible.sync="dialogFormVisible">
      <!-- form表单 -->
      <el-form :model="tmForm" :rules="rules" ref="messageForm" style="width: 80%;">

        <el-form-item prop="tmName" label="品牌名称:" :label-width="formLabelWidth">
          <el-input v-model="tmForm.tmName" autocomplete="off"></el-input>
        </el-form-item>

        <!-- 上传 -->
        <el-form-item prop="logoUrl" label="品牌LOGO:" :label-width="formLabelWidth">
          <el-upload class="avatar-uploader" action="/dev-api/admin/product/fileUpload" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :on-progress="handleUploadProgress">
            <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            <div v-if="isUpload" class="upload-progress-container">
              <el-progress type="circle" :percentage="uploadProgress"></el-progress>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAddOrUpdateTrademark('messageForm')">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>
<script>
export default {
  name: "tradeMark",
  mounted() {
    this.getPageList();
  },
  data() {
    var validateTmName = (rule, value, callback) => {
      if (value.trim().length < 2 || value.trim().length > 10) {
        return callback(new Error('品牌名称字数必须大于 2 小于 10'))
      } else {
        return callback();
      }
    };
    return {
      pageInfo: {
        page: 1,
        limit: 3,
        total: 0,
      },
      tableData: [],
      loading: true,
      // dialog显示与隐藏
      dialogFormVisible: false,
      tmForm: {
        tmName: '',
        logoUrl: '',
      },
      // 表单验证
      rules: {
        tmName: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' },
          // 自定义效验规则
          { validator: validateTmName, trigger: 'change' }
        ],
        logoUrl: [
          { required: true, message: '请上传品牌的图片' }
        ],
      },
      // 控制表单label宽度
      formLabelWidth: '100px',
      // 控制进度的显示
      isUpload: false,
      // 控制上传进度条
      uploadProgress: 0,
      editType: '',
    }
  },
  methods: {
    // 获取分页信息
    async getPageList() {
      this.loading = true;
      // 如果写了.sync 会自动更新pageInfo.page中的值，因此不需要手动更新
      // this.pageInfo.page = curPage;
      const { page, limit } = this.pageInfo;
      let res = await this.$API.trademark.reqTrademarkList(page, limit);
      if (res.code == 200) {
        this.pageInfo.total = res.data.total;
        this.tableData = res.data.records;
        this.loading = false;
      }
    },
    handleEdit(row) {
      this.editType = '修改品牌'
      this.dialogFormVisible = true;
      this.tmForm = { ...row };
    },
    handleDelete(row) {
      this.$confirm(`你确定删除${row.tmName}品牌吗`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await this.$API.trademark.reqDeleteTrademark(row.id)
        if (res.code == 200) {
          if (this.tableData.length == 1) this.pageInfo.page = this.pageInfo.page - 1;
          this.getPageList();
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    showDialog() {
      // 每次打开要清掉之前的数据
      this.editType = '添加品牌'
      this.tmForm = { tmName: '', logoUrl: '' };
      this.dialogFormVisible = true;
    },

    // 处理上传成功
    handleAvatarSuccess(res, file) {
      // console.log(URL.createObjectURL(file.raw));
      this.tmForm.logoUrl = res.data;
      this.isUpload = false;
    },
    // 处理上传之前
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;
      this.isUpload = true;
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
        this.isUpload = false;
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
        this.isUpload = false;
      }
      return isJPG && isLt2M;
    },
    handleUploadProgress(event) {
      this.uploadProgress = event.percent;
    },
    // 上传和修改
    handleAddOrUpdateTrademark(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let res = await this.$API.trademark.reqUpdateTrademark(this.tmForm);
          if (res.code == 200) {
            this.dialogFormVisible = false;
            this.$message({ message: `恭喜你，${this.editType}成功`, type: 'success' });
            if (this.editType == '添加品牌') {
              this.pageInfo.page = 1;
            }
            this.getPageList();
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
  },
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style lang="scss" scoped>
.upload-progress-container {
  position: absolute;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba($color: #fff, $alpha: 1);
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>